﻿using System;
using System.Collections.Generic;
using System.Linq;
using BSDS.Core.Model.Services.Jobs;
using BSDS.Core.Model.Services.Jobs.Core;

namespace BSDS.Commands.Commands.Implementation.Jobs
{
    public class CheckJobsCommand : CommandBase
    {
        private readonly JobRepository jobRepository;
        private readonly JobService jobService;

        public CheckJobsCommand(JobRepository jobRepository, JobService jobService)
        {
            this.jobRepository = jobRepository;
            this.jobService = jobService;
        }

        private Dictionary<Job, string> CheckJobs(IEnumerable<Job> jobs)
        {
            var results = new Dictionary<Job, string>();

            foreach (var job in jobs)
            {
                try
                {
                    var message = jobService.GetShortDetailsMessage(job.Id);

                    results.Add(job, message);
                }
                catch (Exception e)
                {
                    var message = string.Format("{0} Job {1}: error querying state: {2}", job.JobTypeName, job.Id, e.Message);

                    Console.WriteLine(message);
                }
            }

            return results;
        }

        public override CommandResult Execute(ExecutionContext context)
        {
            var results = new Dictionary<Job, string>();

            var geocodeResults = CheckJobs(jobRepository.GetAllGeocodeJobs());
            var uploadResults  = CheckJobs(jobRepository.GetAllUploadJobs());
            var downloadResults = CheckJobs(jobRepository.GetAllDownloadJobs());
            
            geocodeResults.Keys.ToList().ForEach(j => results.Add(j, geocodeResults[j]));
            uploadResults.Keys.ToList().ForEach(j => results.Add(j, uploadResults[j]));
            downloadResults.Keys.ToList().ForEach(j => results.Add(j, downloadResults[j]));

            var sortedStatuses = results.OrderBy(vp => vp.Key.SubmissionDate);

            foreach (var status in sortedStatuses)
            {
                Console.WriteLine(status.Value);
            }

            return CommandResult.Success();
        }
    }
}